package com.firstresponder.util;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

import android.util.Log;

public class SmsDecoder {

	private String smsMessage;
	private Map<SmsConstants, String> map = new EnumMap<SmsConstants, String>(
			SmsConstants.class);
	private boolean isSmsMessage = true;

	public SmsDecoder(String smsMessage) {
		this.smsMessage = smsMessage;
		decode();
	}

	private String get(SmsConstants smsConstant) {

		if (map.containsKey(smsConstant)) {
			return map.get(smsConstant);
		}

		// return null;
		return "";
	}

	public boolean isSmsMessage() {
		return isSmsMessage;
	}

	private void decode() {
		if (smsMessage.startsWith(SmsConstants.HEADER.asSmsAbbreviation())
				&& smsMessage.endsWith(SmsConstants.FOOTER.asSmsAbbreviation())) {
			String[] parts = smsMessage.split(SmsConstants.SEPERATOR
					.asSmsAbbreviation());

			for (String part : parts) {
				if (part.contains("=")) {
					String[] keyVal = part.split("=");
					SmsConstants smsConstant = SmsConstants
							.smsAbbreviationToConstant(keyVal[0]);

					if (smsConstant != null) {
						map.put(smsConstant, keyVal[1]);
					}
				}
			}
		}
	}

	public boolean isAlertMessage() {
		return !get(SmsConstants.ADDRESS).equals("")
				&& !get(SmsConstants.YES_NUMBER).equals("")
				&& !get(SmsConstants.NO_NUMBER).equals("");
	}

	public boolean isCancelMessage() {
		return get(SmsConstants.CANCEL).equals("TRUE");
	}

	public boolean isUpdateDestination() {
		return get(SmsConstants.LOCATION_TYPE).equals("DEST")
				&& !get(SmsConstants.LATITUDE).equals("")
				&& !get(SmsConstants.LONGITUDE).equals("");
	}

	public boolean isAddDbDestination() {
		return !get(SmsConstants.LOCATION_KEY).equals("")
				&& !get(SmsConstants.LOCATION_NAME).equals("")
				&& !get(SmsConstants.LOCATION_PRIORITY).equals("")
				&& !get(SmsConstants.DEPT_ID).equals("")
				&& !get(SmsConstants.LONGITUDE).equals("")
				&& !get(SmsConstants.LATITUDE).equals("");
	}

	public ArrayList<String> getDestCoordinates() {
		ArrayList<String> coordinates = new ArrayList<String>();
		coordinates.add(get(SmsConstants.LATITUDE));
		coordinates.add(get(SmsConstants.LONGITUDE));
		return coordinates;
	}

	public Map<String, String> getNewDestination() {
		Map<String, String> destmap = new HashMap<String, String>();
		destmap.put("lat", get(SmsConstants.LATITUDE));
		destmap.put("long", get(SmsConstants.LONGITUDE));
		destmap.put("dept_id", get(SmsConstants.DEPT_ID));
		destmap.put("loc_key", get(SmsConstants.LOCATION_KEY));
		destmap.put("loc_pr", get(SmsConstants.LOCATION_PRIORITY));
		destmap.put("loc_name", get(SmsConstants.LOCATION_NAME));
		return destmap;
	}

	public String getYesNumber() {
		return get(SmsConstants.YES_NUMBER);
	}
	
	public String getNoNumber(){
		return get(SmsConstants.NO_NUMBER);
	}

}
